<?php

namespace App\Http\Models;

use Illuminate\Database\Eloquent\Model;

/**
 * Trait SafeSave
 * @package App\Http\Models
 * @mixin Model
 */
trait SafeSave
{
    /**
     * @param array $attributes
     * @param array $options
     * @param bool $affect_primary_key
     * @return bool
     */
    public function safeUpdate(array $attributes = [], array $options = [], $affect_primary_key = false)
    {
        $table_columns_array = \Schema::getColumnListing($this->getTable());
        $this->fillable($table_columns_array);

        if (! $this->exists) {
            return false;
        }

        // protect primary key eg. id change by unexpected input
        if (! $affect_primary_key) {
            if (array_key_exists($this->getKeyName(), $attributes)) {
                unset($attributes[$this->getKeyName()]);
            }
        }

        return $this->fill($attributes)->save($options);
    }

    /**
     * @param array $attributes
     * @param bool $affect_primary_key
     * @return mixed
     */
    public static function safeCreate(array $attributes = [], $affect_primary_key = false)
    {
        $table_columns_array = \Schema::getColumnListing((new static)->getTable());

        $fillable_attributes = collect($attributes)
            ->only($table_columns_array)
            ->all();

        // protect primary key eg. id change by unexpected input
        if (! $affect_primary_key) {
            $self = (new self);
            if (array_key_exists($self->getKeyName(), $attributes)) {
                unset($attributes[$self->getKeyName()]);
            }
        }

        return self::create($fillable_attributes);
    }


}
